const app = getApp()
const WXAPI = require("../../../api/newApi")
Page({

  /**
   * 页面的初始数据
   */
  data: {
    list:[],
    bls:[{},{},{}],
    blsIshow: false,
    assetId: '',
    pageSize: 10,
    pageNum: 1,
    total: 0,
    lodingtype: 1,//加载状态（0：加载中  1：加载完成没有更多）
    imgHttp: app.globalData.imgHttp, //图片前缀
    numList: [],
    show: false, //显示明细字段
    worthTotla: 0, //价值合计数量
    getTotalnum: 0,//获得合计数量
    consumeTotal: 0, //消耗合计数量
    buttomShow: false,
    fromLs: [],
    usable: 0,
    isCanUse:'',//是否展示立即使用按钮
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      statusHeight: app.gettop.height,
      status: app.gettop.status,
      navHeight:app.gettop.navHeight,
      mobbleBottom: app.mobile.mobbleBottom
    })
    console.log(options.id)
    this.data.assetId = options.id
    this.data.isCanUse = options.iscanuse
    this.data.usable = options.usable
    this.getLs()
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    console.log("触底了",this.data.pageNum,Math.ceil(this.data.total / this.data.pageSize),this.data.total)
    if (this.data.pageNum >= Math.ceil(this.data.total / this.data.pageSize)) {
      console.log('没有分页')
      this.setData({
        lodingtype: 1
      })
    } else {
      this.setData({
        lodingtype: 0
      })
      this.data.pageNum++; //每触底一次 page + 1;
      this.getLs();
    }
  },
  getLs() {
    wx.showLoading({
      title: '加载中',
    })
    var data = {
      pageNum: this.data.pageNum,
      pageSize: this.data.pageSize,
      assetId: this.data.assetId,
    }
    WXAPI.assetLinkageList(data, (res) => {
      const data = res.result
      if (res.code == 200) {
        if(res.result==''){
          this.setData({
            ls:''
          })
        }
        this.data.total = res.result.total
        let list = res.result.records.map((item, index)=>{
          return {
            ...item,
            getNum: 0,
            consumeNum: 0
          }
        })
        if (this.data.pageNum > 1) {
          this.data.list = this.data.list.concat(list); //将数据拼接在一起
          // this.data.numList = this.data.list.map((item, index)=>{
          //   return {
          //     ...item,
          //     getNum: 0,
          //     consumeNum: 0
          //   }
          // })
          this.setData({
            ls: this.data.list
          })
        } else {
          this.data.list = list
          this.setData({
            ls: this.data.list
          })
        }
        console.log(this.data.list)
        wx.hideLoading({})
      }
    })
  },
  addCount(e){  //增加数量
    const index = e.currentTarget.dataset.index;
    console.log(index)
    let carts = this.data.list;
    let amount = parseInt(carts[index].getNum);
    amount = amount + 1;
    carts[index].getNum = amount;
    if(carts[index].getNum>0){
      this.setData({
        show:true,
      })
    }else{
      this.setData({
        show:false,
      })
    }
    let getTotalnum = this.countTotal(carts)
    let worthTotla = parseInt(this.getTotalPrice(carts))
    let consumeTotal = parseInt(this.getTotalConsume(carts))
    if(getTotalnum>0){
      this.setData({
        buttomShow: true
      })
    }else{
      this.setData({
        buttomShow: false
      })
    }
    console.log(getTotalnum);
    this.setData({
      ls: carts,
      getTotalnum,
      worthTotla,
      consumeTotal
    });
  },
  minusCount(e){ //减少数量
    const index = e.currentTarget.dataset.index;
    let carts = this.data.list;
    let amount = carts[index].getNum;
    if(amount <= 0){
      return false;
    }
    amount = amount - 1;
    carts[index].getNum = amount;
    if(carts[index].getNum>0){
      this.setData({
        show:true,
      })
    }else{
      this.setData({
        show:false,
      })
    }
    let getTotalnum = parseInt(this.countTotal(carts))
    let worthTotla = parseInt(this.getTotalPrice(carts))
    let consumeTotal = parseInt(this.getTotalConsume(carts))
    if(getTotalnum>0){
      this.setData({
        buttomShow: true
      })
    }else{
      this.setData({
        buttomShow: false
      })
    }
    console.log(getTotalnum);
    this.setData({
      ls: carts,
      getTotalnum,
      worthTotla,
      consumeTotal
    });
  },
  bindinput(e){ //输入
    const index = e.currentTarget.dataset.index;
    // let value = e.detail.value
    let value = parseInt(e.detail.value)
    let cls = this.data.list;
    // cls[index].getNum = value
    if(value>cls[index].usable){
      cls[index].getNum = cls[index].usable
      wx.showToast({
        title: '超过最大值，已为您重新修正',
        icon: 'none'
      })
    }else{
      cls[index].getNum = value
    }
    if(cls[index].getNum>0){
      this.setData({
        show:true,
      })
    }else{
      this.setData({
        show:false,
      })
    }
    let getTotalnum = parseInt(this.countTotal(cls))
    console.log(typeof(getTotalnum))
    let worthTotla = parseInt(this.getTotalPrice(cls))
    let consumeTotal = parseInt(this.getTotalConsume(cls))
    if(getTotalnum>0){
      this.setData({
        buttomShow: true
      })
    }else{
      this.setData({
        buttomShow: false
      })
    }
    console.log(getTotalnum);
    this.setData({
      ls: cls,
      getTotalnum,
      worthTotla,
      consumeTotal
    });
    // let amount = carts[index].amount;
  },
  getexchange(){ //立即兑换
    console.log(this.data.consumeTotal)
    console.log(this.data.list)
    if(this.data.usable<this.data.consumeTotal){
      wx.showToast({
        title: '积分数量不足',
        icon:'none'
      })
      return
    }
    let ls = this.data.list.filter((item, index)=>{
      if(item.getNum>0){
        return {
          ...item,
        }
      }
    })
    console.log(ls)
    this.data.fromLs = ls.map((item,index)=>{
      return {
        assetName: item.linkageAssetName,
        linkageId: item.linkageId,
        linkageAssetId: item.linkageAssetId,
        rule: item.rule,
        ratio: item.ratio,
        number: item.getNum,
        worth: item.worth
      }
    })
    console.log( this.data.fromLs)
    let fls = JSON.stringify(this.data.fromLs)
    wx.navigateTo({
      // url: '/userPageA/pages/exchange_detail/exchange_detail',
      url: '/userPageA/pages/exchange_detail/exchange_detail?assetId='+this.data.assetId+"&num="+ this.data.consumeTotal +'&list='+ fls + '&iscanuse=' + this.data.isCanUse,
    })
  },
  back(){
    wx.navigateBack({
      delta: 0,
    })
  },
  openDetail(){ //打开明细
    console.log(this.data.list)
    let detailLs = this.data.list.filter((item, index)=>{
      if(item.getNum>0){
        return {
          ...item,
        }
      }
    })
    console.log(detailLs)
    this.setData({
      blsIshow: true,
      detailLs
    })
  },
  closeDetail(){ //关闭明细
    this.setData({
      blsIshow: false
    })
  },
  // countTotal(arr, keyName){ //计算和
  //   let $total = 0;
	//   $total = arr.reduce(function (total, currentValue, currentIndex, arr){
	//     return currentValue[keyName] ? (total + currentValue[keyName]) : total;
	//   }, 0);
	//   return $total;
  // },
  countTotal(arr) { //计算总数量
    let carts = arr;
    let total = 0;
    for(let i = 0; i<carts.length; i++) {
        total += parseInt(carts[i].getNum)    // 所有价格加起来
    }
    console.log(typeof(total))
    return total;
  },
  getTotalPrice(arr) { //计算总价值
    let carts = arr;
    let total = 0;
    for(let i = 0; i<carts.length; i++) {
      total += carts[i].getNum * carts[i].worth;
    }
    return total;
  },
  getTotalConsume(arr) { //计算总消耗数量
    let carts = arr;
    let total = 0;
    for(let i = 0; i<carts.length; i++) {
      total += carts[i].getNum * carts[i].exchangeRatio;
    }
    return total;
  }
})